package com.njust.RateMyTray_backend.controller;

import com.njust.RateMyTray_backend.common.Result;
import com.njust.RateMyTray_backend.config.CurrentUser;
import com.njust.RateMyTray_backend.dto.CommentCreateDTO;
import com.njust.RateMyTray_backend.dto.ReplyCreateDTO;
import com.njust.RateMyTray_backend.entity.Comment;
import com.njust.RateMyTray_backend.entity.User;
import com.njust.RateMyTray_backend.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/comments")
public class CommentController {
    
    @Autowired
    private CommentService commentService;
    
    @PostMapping
    public ResponseEntity<Result<Map<String, Long>>> createComment(@CurrentUser User currentUser, @RequestBody CommentCreateDTO createDTO) {
        log.info("用户 {} 正在提交评价: {}", currentUser.getUsername(), createDTO);
        Comment newComment = commentService.createComment(currentUser.getId(), createDTO);
        
        Map<String, Long> responseData = Collections.singletonMap("commentId", newComment.getId());
        Result<Map<String, Long>> result = Result.success(201, "评价提交成功", responseData);
        
        return new ResponseEntity<>(result, HttpStatus.CREATED);
    }

    @PostMapping("/{commentId}/like")
    public ResponseEntity<Result<Map<String, Integer>>> likeComment(@CurrentUser User currentUser, @PathVariable Long commentId) {
        log.info("用户 {} 正在点赞评价 {}", currentUser.getUsername(), commentId);
        int newLikesCount = commentService.likeComment(currentUser.getId(), commentId);
        
        Map<String, Integer> responseData = Collections.singletonMap("likesCount", newLikesCount);
        Result<Map<String, Integer>> result = Result.success(200, "点赞成功", responseData);
        
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @PostMapping("/{commentId}/reply")
    public ResponseEntity<Result<Void>> replyToComment(
            @CurrentUser User currentUser,
            @PathVariable Long commentId,
            @RequestBody ReplyCreateDTO replyDTO) {
        
        log.info("用户 {} 正在回复评论 {}", currentUser.getUsername(), commentId);
        commentService.replyToComment(currentUser.getId(), commentId, replyDTO);
        
        return new ResponseEntity<>(Result.success(200, "回复成功", null), HttpStatus.OK);
    }
} 